package com.whccb.apps.office.document.web;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.ProcessAPIManager;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.HistoryTaskInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.TaskInstance;
import com.actionsoft.bpms.commons.database.RowMapper;
import com.actionsoft.bpms.commons.htmlframework.AlertWindow;
import com.actionsoft.bpms.commons.login.constant.LoginConst;
import com.actionsoft.bpms.commons.mvc.view.ActionWeb;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.commons.pagination.SQLPagination;
import com.actionsoft.bpms.org.cache.DepartmentCache;
import com.actionsoft.bpms.org.cache.UserCache;
import com.actionsoft.bpms.org.model.DepartmentModel;
import com.actionsoft.bpms.org.model.UserModel;
import com.actionsoft.bpms.server.SSOUtil;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.util.ConsolePrinter;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.bpms.util.UUIDGener;
import com.actionsoft.bpms.util.UtilString;
import com.actionsoft.i18n.I18nRes;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.ProcessAPI;
import com.whccb.apps.office.document.ODConstant;
import com.whccb.apps.office.document.util.ODAppUtil;
import com.whccb.apps.office.document.util.ODFileNumUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ODWeb extends ActionWeb {

    public ODWeb() {
    }

    public ODWeb(UserContext uc) {
        super(uc);
    }

    public String getOfficeDocumentRecordType(String sid, String deptid) {
        UserContext user = UserContext.fromSessionId(sid);
        String inWhere = ODAppUtil.getUserDeptSqlInWhere(null,
                user.getDepartmentModel().getId());

        String querySql = " SELECT * FROM BO_WHBK_OD_RECORDTYPE WHERE TYPE='01' AND USESCOPEID in "
                + inWhere;
        List<Map<String, String>> odRecordTypeBoList = DBSql.query(querySql,
                new RowMapper<Map<String, String>>() {
                    @Override
                    public Map<String, String> mapRow(ResultSet rs, int rowNum)
                            throws SQLException {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("ID", rs.getString("ID"));
                        map.put("CODE", rs.getString("CODE"));
                        map.put("NAME", rs.getString("NAME"));
                        return map;
                    }
                });

        ResponseObject ro;
        if (odRecordTypeBoList != null && !odRecordTypeBoList.isEmpty()
                && odRecordTypeBoList.size() > 0) {
            ro = ResponseObject.newOkResponse();
            JSONArray jsons = new JSONArray();
            for (Map<String, String> odRecordTypeMap : odRecordTypeBoList) {
                if (odRecordTypeMap != null && !odRecordTypeMap.isEmpty()) {
                    JSONObject json = new JSONObject();
                    json.put("CODE", odRecordTypeMap.get("CODE"));
                    json.put("NAME", odRecordTypeMap.get("NAME"));
                    json.put("ID", odRecordTypeMap.get("ID"));
                    json.put("PROCESSDEFID", ODConstant.FW_PROCESS_DEF_UUID);
                    jsons.add(json);
                }
            }
            System.out.println("jsons=" + jsons.toString());
            ro.put("odRecordTypes", jsons);
        } else {
            ro = ResponseObject.newErrResponse("未查询到数据");
        }
        return ro.toString();
    }

    public String openFwForm(String processDefId, String title,
            String createUserLocation, String typeId) {
        try {
            BO recordTypeBo = SDK.getBOAPI().get("BO_WHBK_OD_RECORDTYPE",
                    typeId);
            if (recordTypeBo != null) {
                if (processDefId.equals("")) {
                    processDefId = ODConstant.FW_PROCESS_DEF_UUID;
                }
                // 启动流程
                ProcessInstance processInstance = SDK.getProcessAPI()
                        .createProcessInstance(processDefId,
                                this.getContext().getUID(), title);

                // 初始化BO数据
                BO fwBo = SDK.getBOAPI().getByProcess("BO_WHBK_OD_DRAFT",
                        processInstance.getId());
                if (fwBo == null) {
                    String boId = UUIDGener.getUUID();
                    fwBo = new BO();
                    fwBo.setId(boId);
                    fwBo.setBindId(processInstance.getId());
                    fwBo.set("RECORDTYPEID", typeId);
                    fwBo.set("RECORDTYPE", recordTypeBo.getString("NAME"));
                    fwBo.set("FILEFROM", recordTypeBo.getString("FILEFROM"));// 印发单位

                    fwBo.set("USERNAME", this.getContext().getUserName());
                    fwBo.set("USERID", this.getContext().getUID());
                    String at = "@getUserHrDeptInfoByUidAndFlag("
                            + this.getContext().getUID() + ",ALL)";
                    fwBo.set("USERDEPTNAME",
                            SDK.getRuleAPI().executeAtScript(at));// 部门
                    fwBo.set("USERDEPTID",
                            this.getContext().getDepartmentModel().getId());
                    fwBo.set("STATUS", "发文拟稿");
                    fwBo.set("YEAR", SDK.getRuleAPI().executeAtScript("@year"));
                    fwBo.set("MONTH",
                            SDK.getRuleAPI().executeAtScript("@month"));
                    fwBo.set("APPLYDATE",
                            SDK.getRuleAPI().executeAtScript("@date"));
                    fwBo.set("NUM", "");
                    // fwBo.set("SENDTO", "内发");
                    fwBo.set("URGERCY", "平急");
                    // fwBo.set("DENSELEV", "0");
                    fwBo.set("ISONLYDOUSERNAME", "1");
                    SDK.getBOAPI().create("BO_WHBK_OD_DRAFT", fwBo,
                            processInstance, this.getContext());
                }

                SDK.getProcessAPI().start(processInstance);

                TaskInstance taskInstance = null;
                List<TaskInstance> taskList = SDK.getTaskQueryAPI()
                        .processInstId(processInstance.getId())
                        .addQuery("TASKSTATE !=", "9").list();
                if (taskList != null && !taskList.isEmpty()
                        && taskList.size() > 0) {
                    for (TaskInstance task : taskList) {
                        if (task != null) {
                            taskInstance = task;
                            break;
                        }
                    }
                }
                return SDK.getFormAPI().getFormPage(this.getContext(),
                        processInstance, taskInstance, 1, 1, null, null, null,
                        true);
            } else {
                return AlertWindow.getPage("提示",
                        I18nRes.findValue(super.getContext().getLanguage(),
                                "公文文种不存在") + "!",
                        "../commons/img/warning2_96.png");
            }
        } catch (Exception e) {
            return AlertWindow.getPage("提示",
                    I18nRes.findValue(super.getContext().getLanguage(),
                            e.getMessage()) + "!",
                    "../commons/img/warning2_96.png");
        }

    }

    public String modifyOfficeDocumentFileNum(String bindid, String boName,
            String recordTypeId, String year, String flag, String fileNum) {
        BO fwBo = SDK.getBOAPI().getByProcess(boName, bindid);
        int num = 0;
        try {
            num = Integer.parseInt(fileNum);
        } catch (Exception e) {

        }
        ResponseObject ro;
        ODFileNumUtil fileNumUtil = new ODFileNumUtil();
        if (fileNumUtil.saveOfficeDocumentFileNum(flag, recordTypeId, year, num,
                bindid, boName, this.getContext().getUID())) {
            // 插入跳号记录
            List<BO> boList = SDK.getBOAPI().query("BO_WHBK_OD_FNUM_JUMP")
                    .addQuery("RECORDTYPEID =", recordTypeId)
                    .addQuery("YEAR =", year).addQuery("FILENUM =", num).list();
            if (boList == null || boList.isEmpty() || boList.size() == 0) {
                BO jumpBo = new BO();
                jumpBo.setId(UUIDGener.getUUID());
                jumpBo.set("RECORDTYPEID", recordTypeId);
                jumpBo.set("YEAR", year);
                jumpBo.set("FILENUM", num);
                jumpBo.set("REMARK", "定稿换号");
                SDK.getBOAPI().createDataBO("BO_WHBK_OD_FNUM_JUMP", jumpBo,
                        this.getContext());
            }

            BO recod = SDK.getBOAPI().query("BO_WHBK_OD_RECORDTYPE")
                    .detailById(recordTypeId);

            String odFileNum = "";
            if ("BO_WHBK_EA_INFO_SEND".equals(boName)) {// 信息上报
                odFileNum = "第" + fileNum + "期";
            } else if ("0".equals(recod.getString("RECORDSHOW"))) {
                odFileNum = fileNum + "";
            } else {
                odFileNum = fwBo.getString("RECORDTYPE") + "〔"
                        + fwBo.getString("YEAR") + "〕" + fileNum + " 号 ";
            }
            String updateSql = " UPDATE " + boName
                    + " SET NUM = :NUM,FILENUM=:FILENUM WHERE BINDID = :BINDID ";
            Map<String, Object> updateMap = new HashMap<String, Object>();
            updateMap.put("NUM", fileNum);
            updateMap.put("FILENUM", odFileNum);
            updateMap.put("BINDID", bindid);
            DBSql.update(updateSql, updateMap);
            ro = ResponseObject.newOkResponse();
            ro.put("fileNum", fileNum);
            ro.put("odFileNum", odFileNum);
        } else {
            ro = ResponseObject.newErrResponse("您输入的文号已经存在，请更换。");
        }
        return ro.toString();
    }

    public String modifyOfficeDocumentFileType(String bindid, String boName,
            String recordTypeId, String recordTypeName) {
        ResponseObject ro;
        BO bo = SDK.getBOAPI().getByProcess(boName, bindid);
        if (bo != null) {
            String updateSql = " UPDATE " + boName
                    + " SET RECORDTYPE = :RECORDTYPE,RECORDTYPEID=:RECORDTYPEID WHERE BINDID = :BINDID ";
            Map<String, Object> updateMap = new HashMap<String, Object>();
            updateMap.put("RECORDTYPE", recordTypeName);
            updateMap.put("RECORDTYPEID", recordTypeId);
            updateMap.put("BINDID", bindid);
            DBSql.update(updateSql, updateMap);
            ro = ResponseObject.newOkResponse();
            ro.put("recordTypeId", recordTypeId);
            ro.put("recordTypeName", recordTypeName);
        } else {
            ro = ResponseObject.newErrResponse("参数错误");
        }
        return ro.toString();
    }

    public String gwCmsPage(String processInstId, String taskInstId,
            String formDefId) {
        String formpage = "";
        try {
            ProcessInstance processInst = ProcessAPIManager.getInstance()
                    .getInstance(processInstId);
            if (UtilString.isEmpty(taskInstId)) {
                taskInstId = processInst.getStartTaskInstId();
            }
            boolean isPDF = false;// 暂不考虑pdf格式
            if (isPDF) {
                formpage = SDK.getFormAPI().getFormPage(getContext(),
                        processInstId, taskInstId, 0, 1,
                        ODConstant.FORM_GW_CMS_PDF_DEF_ID, null, null, false);
            } else {
                formpage = SDK.getFormAPI().getFormPage(getContext(),
                        processInstId, taskInstId, 0, 1, formDefId, null, null,
                        false);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return formpage;
    }

    public String checkDownLoadCmsZwPermi(String modelid) {
        ResponseObject ro = ResponseObject.newOkResponse();
        String result = "0";
        BO cmsExtendsBo = SDK.getBOAPI().getByKeyField(
                "BO_WHBK_OD_CMS_MODEL_EXTEND", "CMSMODEL", modelid);
        if (cmsExtendsBo != null) {
            String roleIdStr = cmsExtendsBo.getString("ROLEID");
            if (StringUtils.isNotEmpty(roleIdStr)) {
                String[] roleIds = roleIdStr.split(",");
                ODAppUtil util = new ODAppUtil();
                for (String roleId : roleIds) {
                    if (util.userIsHasRole(this.getContext().getUID(),
                            roleId)) {
                        result = "1";
                        break;
                    }
                }
            }
        }
        ro.setData(result);
        return ro.toString();
    }

    /**
     * 收文流程在主流程中主动增加子流程分支
     * 
     * @param sid
     * @param parentProcessinstid
     * @param parentTaskDefid
     * @param useridstr
     * @return
     */
    public String addsub(String sid, String parentProcessinstid,
            String parentTaskDefid, String useridstr) {
        ResponseObject ro = ResponseObject.newOkResponse();
        BO parentBo = SDK.getBOAPI().getByProcess("BO_WHBK_OD_RECEIVE",
                parentProcessinstid);
        String backMessage = "";
        String queryCallActivityTaskInstId = "select ID from WFC_TASK where PROCESSINSTID = :PROCESSINSTID and ACTIVITYDEFID = :ACTIVITYDEFID ";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("PROCESSINSTID", parentProcessinstid);
        params.put("ACTIVITYDEFID", parentTaskDefid);
        String callActivityTaskInstId = DBSql
                .getString(
                        SQLPagination.getPaginitionSQL(
                                queryCallActivityTaskInstId, 0, 1),
                        "ID", params);
        if (StringUtils.isNotEmpty(useridstr)) {
            String[] userids = useridstr.split(",");
            for (String userid : userids) {
                if (StringUtils.isNotEmpty(userid)
                        && UserCache.getModel(userid) != null) {

                    UserModel user = UserCache.getModel(userid);
                    DepartmentModel dept = DepartmentCache
                            .getModel(user.getDepartmentId());
                    ProcessInstance subProcessInst = SDK.getProcessAPI()
                            .createSubProcessInstance(userid, "追加收文办理流程",
                                    callActivityTaskInstId, null);
                    // 同步BO数据
                    SDK.getBOAPI().query("BO_WHBK_OD_RECEIVE", true)
                            .addQuery("BINDID =", parentProcessinstid)
                            .copyTo("BO_WHBK_OD_RECEIVE_DO",
                                    subProcessInst.getId())
                            .removeMapping("HQ").removeMapping("DOFILE").exec();

                    SDK.getProcessAPI().start(subProcessInst);
                    BO subBo = SDK.getBOAPI().getByProcess(
                            "BO_WHBK_OD_RECEIVE_DO", subProcessInst.getId());
                    // 将填加的账户同步加至主流程的会签经理
                    if (parentBo != null) {
                        String doUserName = parentBo.getString("DOUSERNAME");
                        String doUserId = parentBo.getString("DOUSERID");
                        if (StringUtils.isNotEmpty(doUserName.trim())) {
                            doUserName = doUserName + "," + user.getUserName();
                        } else {
                            doUserName = user.getUserName();
                        }
                        if (StringUtils.isNotEmpty(doUserId.trim())) {
                            doUserId = doUserId + "," + userid;
                        } else {
                            doUserId = userid;
                        }

                        parentBo.set("DOUSERNAME", doUserName);
                        parentBo.set("DOUSERID", doUserId);
                        String updateSql = " UPDATE BO_WHBK_OD_RECEIVE SET DOUSERNAME =:DOUSERNAME,DOUSERID=:DOUSERID WHERE ID = :ID ";
                        Map<String, Object> param = new HashMap<String, Object>();
                        param.put("DOUSERNAME", doUserName);
                        param.put("DOUSERID", doUserId);
                        param.put("ID", parentBo.getId());
                        DBSql.update(updateSql, param);

                        // 同步处理签批信息
                        // 构建父流程的签批DC，将其复制到子流程相应位置。
                        String parentDCGroupValue = parentBo.getBindId();
                        String parentDCFileValue = parentBo.getId();
                        String subDCGroupValue = subBo.getBindId();
                        String subDCFileValue = subBo.getId();

                        Map<String, String> leaderSignMap = null;
                        String queryParentHwSql = " SELECT ID,BINDID,BOID,APPID,BOITEMNAME,TASKINSTID,CREATEUSER,CREATETIME,FILENAME,SIGNUSER,SIGNTIME,NOWTYPE,DATA,QRCODE,USERMZ,SORT FROM APP_ACT_HWSIGNATURE_DATA WHERE BINDID = :BINDID AND BOITEMNAME = :BOITEMNAME ";
                        Map<String, Object> paramMap = new HashMap<String, Object>();
                        paramMap.put("BINDID", parentBo.getBindId());
                        paramMap.put("BOITEMNAME", "LEADERSIGN");
                        List<Map<String, String>> leaderSignList = DBSql.query(
                                queryParentHwSql, paramMap,
                                new RowMapper<Map<String, String>>() {
                                    public Map<String, String> mapRow(
                                            ResultSet rs, int index)
                                                    throws SQLException {
                                        Map<String, String> map = new HashMap<String, String>();
                                        map.put("ID", rs.getString("ID"));
                                        map.put("BINDID",
                                                rs.getString("BINDID"));
                                        map.put("BOID", rs.getString("BOID"));
                                        map.put("APPID", rs.getString("APPID"));
                                        map.put("BOITEMNAME",
                                                rs.getString("BOITEMNAME"));
                                        map.put("TASKINSTID",
                                                rs.getString("TASKINSTID"));
                                        map.put("CREATEUSER",
                                                rs.getString("CREATEUSER"));
                                        map.put("CREATETIME",
                                                rs.getString("CREATETIME"));
                                        map.put("FILENAME",
                                                rs.getString("FILENAME"));
                                        map.put("SIGNUSER",
                                                rs.getString("SIGNUSER"));
                                        map.put("SIGNTIME",
                                                rs.getString("SIGNTIME"));
                                        map.put("NOWTYPE",
                                                rs.getString("NOWTYPE"));
                                        map.put("DATA", rs.getString("DATA"));
                                        map.put("QRCODE",
                                                rs.getString("QRCODE"));
                                        map.put("USERMZ",
                                                rs.getString("USERMZ"));
                                        map.put("SORT", rs.getString("SORT"));
                                        return map;
                                    }
                                });

                        if (leaderSignList != null && !leaderSignList.isEmpty()
                                && leaderSignList.size() > 0) {
                            leaderSignMap = leaderSignList.get(0);
                        }

                        if (leaderSignMap != null && !leaderSignMap.isEmpty()) {
                            // 构建父流程的签批DC，将其复制到子流程相应位置。
                            DCContext parentLeaderDc = new DCContext(
                                    UserContext.fromUID("admin"),
                                    SDK.getDCAPI().getDCProfile(
                                            "com.actionsoft.apps.formui.hwsignature",
                                            "-hsingature-"),
                                    ODConstant.APP_ID, parentDCGroupValue,
                                    parentDCFileValue,
                                    leaderSignMap.get("FILENAME"));
                            if (parentLeaderDc != null) {
                                JSONObject insertParamMap = new JSONObject();
                                insertParamMap.put("ID", UUIDGener.getUUID());
                                insertParamMap.put("BINDID", subBo.getBindId());// 子流程实例ID
                                insertParamMap.put("BOID", subBo.getId());// 子流程的BO记录ID
                                insertParamMap.put("APPID",
                                        leaderSignMap.get("APPID"));
                                insertParamMap.put("BOITEMNAME", "LEADERSIGN");
                                insertParamMap.put("TASKINSTID", "xxxx");
                                insertParamMap.put("CREATEUSER",
                                        leaderSignMap.get("CREATEUSER"));
                                insertParamMap.put("CREATETIME",
                                        leaderSignMap.get("CREATETIME"));
                                insertParamMap.put("FILENAME",
                                        leaderSignMap.get("FILENAME"));
                                insertParamMap.put("SIGNUSER",
                                        leaderSignMap.get("SIGNUSER"));
                                insertParamMap.put("SIGNTIME",
                                        leaderSignMap.get("SIGNTIME"));
                                insertParamMap.put("NOWTYPE",
                                        leaderSignMap.get("NOWTYPE"));
                                insertParamMap.put("DATA",
                                        leaderSignMap.get("DATA"));
                                insertParamMap.put("QRCODE",
                                        leaderSignMap.get("QRCODE"));
                                insertParamMap.put("USERMZ",
                                        leaderSignMap.get("USERMZ"));
                                insertParamMap.put("SORT",
                                        leaderSignMap.get("SORT"));
                                // 调用App
                                String sourceAppId = "com.actionsoft.apps.formui.hwsignature";
                                // aslp服务地址
                                String aslp = "aslp://com.actionsoft.apps.formui.hwsignature/saveHwData";
                                // 参数定义列表
                                Map<String, Object> aslpParams = new HashMap<String, Object>();
                                // 手写签批json信息，不允许空值,必填
                                aslpParams.put("hwjson",
                                        insertParamMap.toString());
                                // 插入手写签批数据库记录
                                ResponseObject hwAslpRo = SDK.getAppAPI()
                                        .callASLP(
                                                SDK.getAppAPI().getAppContext(
                                                        sourceAppId),
                                                aslp, aslpParams);

                                // 复制签批DC
                                DCContext subLeaderDc = new DCContext(
                                        UserContext.fromUID("admin"),
                                        SDK.getDCAPI().getDCProfile(
                                                "com.actionsoft.apps.formui.hwsignature",
                                                "-hsingature-"),
                                        ODConstant.APP_ID, subDCGroupValue,
                                        subDCFileValue,
                                        leaderSignMap.get("FILENAME"));
                                subLeaderDc.delete();
                                SDK.getDCAPI().copyDCFile(parentLeaderDc,
                                        subLeaderDc);
                            }
                        }

                    }
                    backMessage = "添加成功，请通过跟踪图并刷新页面查看";
                } else {
                    backMessage = "填写的帐号不合法";
                }
            }
        } else {
            backMessage = "填写的帐号为空";
        }
        ro.put("backMessage", backMessage);
        return ro.toString();
    }

    /**
     * 收文流程在主流程中主动删除子流程分支
     * 
     * @param sid
     * @param parentProcessinstid
     * @param parentTaskDefid
     * @param useridstr
     * @return
     */
    public String delsub(String sid, String parentProcessinstid,
            String parentTaskDefid, String useridstr) {
        ResponseObject ro = ResponseObject.newOkResponse();
        BO parentBo = SDK.getBOAPI().getByProcess("BO_WHBK_OD_RECEIVE",
                parentProcessinstid);
        String backMessage = "";
        String queryCallActivityTaskInstId = "select ID from WFC_TASK where PROCESSINSTID = :PROCESSINSTID and ACTIVITYDEFID = :ACTIVITYDEFID ";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("PROCESSINSTID", parentProcessinstid);
        params.put("ACTIVITYDEFID", parentTaskDefid);
        String callActivityTaskInstId = DBSql
                .getString(
                        SQLPagination.getPaginitionSQL(
                                queryCallActivityTaskInstId, 0, 1),
                        "ID", params);
        List<ProcessInstance> subProcessList = SDK.getProcessAPI().query()
                .parentProcessInstId(parentProcessinstid)
                .parentTaskInstId(callActivityTaskInstId).list();

        if (subProcessList != null && !subProcessList.isEmpty()
                && subProcessList.size() > 0) {
            if (StringUtils.isNotEmpty(useridstr)) {
                String[] userids = useridstr.split(",");
                for (ProcessInstance subProcessinst : subProcessList) {
                    if (subProcessinst != null) {
                        for (String userid : userids) {
                            UserModel user = UserCache.getModel(userid);
                            DepartmentModel dept = DepartmentCache
                                    .getModel(user.getDepartmentId());
                            if (subProcessinst.getCreateUser().equals(userid)) {
                                SDK.getProcessAPI().deleteById(
                                        subProcessinst.getId(), userid);
                                // 将删除的账户同步更新至主流程的承办人员、承办部门字段
                                if (parentBo != null) {
                                    String doUserName = parentBo
                                            .getString("DOUSERNAME");
                                    String doUserId = parentBo
                                            .getString("DOUSERID");
                                    String doUserNameNew = "";
                                    String doUserIdNew = "";
                                    if (StringUtils.isNotEmpty(doUserId)) {
                                        String[] doUserIds = doUserId
                                                .split(",");
                                        String[] doUserNames = doUserName
                                                .split(",");
                                        if (doUserIds != null
                                                && doUserIds.length > 0) {
                                            for (int i = 0; i < doUserIds.length; i++) {
                                                if (!userid.trim().equals(
                                                        doUserIds[i].trim())) {
                                                    if (StringUtils.isNotEmpty(
                                                            doUserIdNew)) {
                                                        doUserIdNew = doUserIdNew
                                                                + ","
                                                                + doUserIds[i]
                                                                        .trim();
                                                    } else {
                                                        doUserIdNew = doUserIds[i]
                                                                .trim();
                                                    }

                                                    if (doUserNames != null
                                                            && doUserNames.length > i) {
                                                        if (StringUtils
                                                                .isNotEmpty(
                                                                        doUserNameNew)) {
                                                            doUserNameNew = doUserNameNew
                                                                    + ","
                                                                    + doUserNames[i]
                                                                            .trim();
                                                        } else {
                                                            doUserNameNew = doUserNames[i]
                                                                    .trim();
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    parentBo.set("DOUSERNAME", doUserNameNew);
                                    parentBo.set("DOUSERID", doUserIdNew);
                                    String updateSql = " UPDATE BO_WHBK_OD_RECEIVE SET DOUSERNAME =:DOUSERNAME,DOUSERID=:DOUSERID WHERE ID = :ID ";
                                    Map<String, Object> param = new HashMap<String, Object>();
                                    param.put("DOUSERNAME", doUserNameNew);
                                    param.put("DOUSERID", doUserIdNew);
                                    param.put("ID", parentBo.getId());
                                    DBSql.update(updateSql, param);
                                }
                            }
                        }
                    }
                }
                backMessage = "删除成功，请刷新页面并通过跟踪图查看";
            } else {
                backMessage = "填写的帐号为空";
            }
        } else {
            backMessage = "尚未启动承办子流程";
        }
        ro.put("backMessage", backMessage);
        return ro.toString();
    }

    public String getPubPrintPageURL(String sid, String boname, String boid) {
        ResponseObject ro = null;
        BO bo = SDK.getBOAPI().get(boname, boid);
        if (bo != null) {
            String bindid = bo.getBindId();
            String taskId = "";
            String rightUserId = "";
            List<TaskInstance> taskList = SDK.getTaskQueryAPI()
                    .processInstId(bindid).activityType("userTask")
                    .addQuery("TASKSTATE !=", "9").list();
            if (taskList != null && !taskList.isEmpty()
                    && taskList.size() > 0) {
                taskId = taskList.get(0).getId();
                rightUserId = taskList.get(0).getTarget();
            } else {
                List<HistoryTaskInstance> hisTaskList = SDK
                        .getHistoryTaskQueryAPI().processInstId(bindid)
                        .activityType("userTask").addQuery("TASKSTATE !=", "9")
                        .orderBy("ENDTIME").desc().list();
                if (hisTaskList != null && !hisTaskList.isEmpty()
                        && hisTaskList.size() > 0) {
                    taskId = hisTaskList.get(0).getId();
                    rightUserId = hisTaskList.get(0).getTarget();
                }

            }
            String rigthSid = new SSOUtil().registerClientSessionNoPassword(
                    rightUserId, LoginConst.DEFAULT_LANG, "localhost",
                    LoginConst.DEVICE_PC);
            String url = SDK.getFormAPI().getFormURL(
                    SDK.getPlatformAPI().getPortalUrl(), rigthSid, bindid,
                    taskId, 1, null, null, null, false);
            ro = ResponseObject.newOkResponse();
            ro.setData(url);
        } else {
            ro = ResponseObject.newErrResponse("参数不正确");
        }
        return ro.toString();
    }

    public String backProcessTask(String sid, String reason, String boName,
            String bindid, String pointTaskDefid) {
        ResponseObject ro = null;
        UserContext me = UserContext.fromSessionId(sid);
        // 通过BINDID去查询流程变量得到BOname的值
        Map<String, Object> paramMap = SDK.getProcessAPI().getVariables(bindid);
        if (paramMap != null && !paramMap.isEmpty()) {
            boName = paramMap.get("BONAME") != null
                    ? paramMap.get("BONAME").toString() : "";
        }
        // 删除掉CMS的发文信息
        BO bo = SDK.getBOAPI().getByProcess(boName, bindid);
        if (bo != null && bo.get("REFCMSID") != null) {
            String refCmsId = bo.getString("REFCMSID");
            if (StringUtils.isNotEmpty(refCmsId)) {
                BO cmsBo = SDK.getBOAPI().get("BO_ACT_CMS_CONTENT", refCmsId);
                if (cmsBo != null) {
                    String queryDataSql = " SELECT ID FROM APP_ACT_CMS_DATA WHERE BOID = :BOID ";
                    Map<String, Object> param = new HashMap<String, Object>();
                    param.put("BOID", refCmsId);
                    String cmsDataId = DBSql.getString(queryDataSql, "ID",
                            param);
                    // CmsDataCache.removeById(cmsDataId);
                    Map<String, Object> params = new HashMap<String, Object>();
                    // cms记录ID,必填
                    params.put("cmsDataId", cmsDataId);
                    SDK.getAppAPI().callASLP(
                            SDK.getAppAPI()
                                    .getAppContext("com.actionsoft.apps.cms"),
                            "aslp://com.actionsoft.apps.cms/cmsDel", params);
                }
            }
        }
        ProcessAPI api = SDK.getProcessAPI();
        ProcessInstance processInstance = api.getInstanceById(bindid);
        if (StringUtils.isEmpty(pointTaskDefid)) {
            pointTaskDefid = processInstance.getEndActivityId();
        }

        // 收回流程到指定节点 判断是否有活动的任务实例
        List<TaskInstance> tiList = SDK.getTaskQueryAPI().processInstId(bindid)
                .activeTask().list();
        ConsolePrinter.info("任务实例查询---" + tiList.isEmpty());
        ConsolePrinter.info("任务实例查询---" + tiList.size());
        List<HistoryTaskInstance> htqlist = SDK.getHistoryTaskQueryAPI()
                .processInstId(bindid).orderByEndTime().desc().list();
        if (api.isEndById(bindid)
                && (tiList == null || tiList.isEmpty() || tiList.size() < 1)) {

            api.reactivateById(bindid, pointTaskDefid, false, me.getUID(),
                    me.getUID(), reason);

            ro = ResponseObject.newOkResponse();
            ro.setData("收回成功，请刷新页面或从跟踪图查看！");
        } else {
            ro = ResponseObject.newErrResponse("该流程已经收回，请刷新页面！");
        }
        return ro.toString();
    }

    public String toLeaderOptionTask(String sid, String reason, String boName,
            String bindid, String pointTaskDefid) {
        ResponseObject ro = null;
        UserContext me = UserContext.fromSessionId(sid);
        // 通过BINDID去查询流程变量得到BOname的值
        Map<String, Object> paramMap = SDK.getProcessAPI().getVariables(bindid);
        if (paramMap != null && !paramMap.isEmpty()) {
            boName = paramMap.get("BONAME") != null
                    ? paramMap.get("BONAME").toString() : "";
        }
        ProcessAPI api = SDK.getProcessAPI();
        ProcessInstance processInstance = api.getInstanceById(bindid);
        String parentTaskId = processInstance.getStartTaskInstId();
        SDK.getTaskAPI().createUserTaskInstance(bindid, parentTaskId,
                me.getUID(), pointTaskDefid, me.getUID(),
                processInstance.getTitle());
        ro = ResponseObject.newOkResponse();
        ro.setData("任务激活成功，请在待办任务中处理！");
        return ro.toString();
    }

}
